﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2022 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

namespace Abc.Core;

public class EntityChangedListener :
       IEntityChangedListener<SysRole>
     , IEntityChangedListener<SysDataConfig>
     , IEntityChangedListener<SysMenu>
     , IEntityChangedListener<SysRoleMenu>

    , IEntityChangedListener<EmailSendConfig>

{
    public void OnChanged(SysRole newEntity, SysRole oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
    {
        RemoveCache(dbContext, state, newEntity.GetType().Name);
    }

    public void OnChanged(SysDataConfig newEntity, SysDataConfig oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
    {
        RemoveCache(dbContext, state, newEntity.GetType().Name);
    }

    public void OnChanged(SysMenu newEntity, SysMenu oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
    {
        RemoveCache(dbContext, state, newEntity.GetType().Name);
        RemoveCache(dbContext, state, typeof(SysRole).Name);
    }

    /// <summary>
    /// 角色菜单，当角色菜单数据有变化的时候
    /// </summary>
    /// <param name="newEntity"></param>
    /// <param name="oldEntity"></param>
    /// <param name="dbContext"></param>
    /// <param name="dbContextLocator"></param>
    /// <param name="state"></param>
    public void OnChanged(SysRoleMenu newEntity, SysRoleMenu oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
    {
        RemoveCache(dbContext, state, typeof(SysRole).Name);
    }

    public void OnChanged(EmailSendConfig newEntity, EmailSendConfig oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
    {
        RemoveCache(dbContext, state, newEntity.GetType().Name);
    }

    /// <summary>
    /// 移除缓存
    /// </summary>
    /// <param name="entityName"></param>
    private void RemoveCache(DbContext dbContext, EntityState state, string entityName)
    {
        Caches.Remove(Caches.GetTableCacheKey(entityName));
    }
}